// gameSetup.js

export const Vars = {
    X:'',
    Y:'',
    isBlack:'',
    ctx:'',
    W:'',
    SHADOW_COLOR:'',
    BLACK_CHESS_TOP_COLOR:'',
    WHITE_CHESS_TOP_COLOR:'',
    BLACK_CHESS_COLOR:'',
    WHITE_CHESS_COLOR:'',
    BOARD_BG_COLOR:null,
    IDa:null,
    IDb:null,
    currentPlayer:null,
    MyID:null,
    A_steps:null,
    B_steps:null,
    BOT_ID:null,
    isBot:false,
    store:null,
    SL:null,
    LINE_WIDTH:null,
    LINE_COLOR:null,
    WIN_LINE_WIDTH:null,
    WIN_LINE_COLOR:null,
    TOTAL_STEPS:null
};

let
    SIZE = 15,
    EMPTY_ROLE = -1,
    chess = Array.from({ length: SIZE }, () => Array(SIZE).fill(EMPTY_ROLE)),
    isBlack = true,
    moveSteps = 0;

export function initializeGame(canvas,store) {
    Vars.store =store;
    const
        W = Math.min(window.innerWidth, window.innerHeight) / (SIZE + 3),
        SL = W * (SIZE + 1),
        BOARD_BG_COLOR = '#E4A751',
        LINE_WIDTH = 1,
        LINE_COLOR = '#000000',
        WIN_LINE_WIDTH = 5,
        WIN_LINE_COLOR = '#F05459',
        BLACK_CHESS_COLOR = '#000000',
        BLACK_CHESS_TOP_COLOR = '#707070',
        WHITE_CHESS_COLOR = '#D5D8DC',
        WHITE_CHESS_TOP_COLOR = '#FFFFFF',
        SHADOW_COLOR = 'rgba(0, 0, 0, 0.5)',
        BLACK_ROLE = 1,
        WHITE_ROLE = 2,
        TOTAL_STEPS = SIZE * SIZE;

    const ctx = canvas.getContext('2d');
    Vars.ctx = ctx;
    Vars.W = W;
    Vars.SHADOW_COLOR = SHADOW_COLOR;
    Vars.BLACK_CHESS_COLOR = BLACK_CHESS_COLOR;
    Vars.BLACK_CHESS_TOP_COLOR = BLACK_CHESS_TOP_COLOR;
    Vars.WHITE_CHESS_COLOR = WHITE_CHESS_COLOR;
    Vars.WHITE_CHESS_TOP_COLOR = WHITE_CHESS_TOP_COLOR;
    Vars.SL = SL;
    Vars.BOARD_BG_COLOR=BOARD_BG_COLOR;
    Vars.LINE_WIDTH=LINE_WIDTH;
    Vars.LINE_COLOR=LINE_COLOR;
    Vars.WIN_LINE_WIDTH=WIN_LINE_WIDTH;
    Vars.WIN_LINE_COLOR=WIN_LINE_COLOR;
    Vars.TOTAL_STEPS= TOTAL_STEPS;


    canvas.width = canvas.height = SL;
    canvas.style.cssText = 'position: absolute; inset: 0; margin: auto; cursor: pointer;';
    // document.body.appendChild(canvas);



    canvas.onclick = e => {
            isBlack = Vars.isBlack;
            let [x, y] = [e.offsetX, e.offsetY].map(p => Math.round(p / W) - 1);
            //同位置禁止重复下棋
            if (chess[x]?.[y] !== EMPTY_ROLE) return;
            // 不是当前玩家的回合
            if (Vars.MyID !== Vars.currentPlayer) return;
            store.state.pk.socket.send(JSON.stringify({//将JSON转换为字符串
                    event: "move",
                    x: x,
                    y: y,
                    isBlack: isBlack,
                }))

            drawPiece(x, y, isBlack);
            chess[x][y] = isBlack ? BLACK_ROLE : WHITE_ROLE;
        if (isWin(x, y, chess[x][y], chess)) {
            // 发送胜利结果到服务器
            store.state.pk.socket.send(JSON.stringify({
                event: "finish",
                result: `${isBlack ? '黑' : '白'}棋赢了!`,
                isBlack: isBlack
            }));
        } else if (++moveSteps === TOTAL_STEPS) {
            // 发送平局结果到服务器
            store.state.pk.socket.send(JSON.stringify({
                event: "finish",
                result: '游戏结束，平局！',
                isBlack: null // 平局时可以设置为 null
            }));
        }
    }

    const drawBoard = () => {
        ctx.fillStyle = BOARD_BG_COLOR;
        ctx.fillRect(0, 0, SL, SL);
        for (let i = 0; i < SIZE; i++) {
            drawLine(0, i, SIZE - 1, i);
            drawLine(i, 0, i, SIZE - 1);
        }
    }

    const drawLine = (x1, y1, x2, y2, lineWidth = LINE_WIDTH, lineColor = LINE_COLOR) => {
        ctx.lineWidth = lineWidth;
        ctx.strokeStyle = lineColor;
        ctx.beginPath();
        ctx.moveTo(x1 * W + W, y1 * W + W);
        ctx.lineTo(x2 * W + W, y2 * W + W);
        ctx.stroke();
    }



    const isWin = (x, y, role, chess) => [[1, 0], [0, 1], [1, 1], [1, -1]].some(([dx, dy]) => {
        let count = 1, i = 0, j = 0;
        while(count < 5 && chess[x + dx * ++i]?.[y + dy * i] === role) count++;
        while(count < 5 && chess[x - dx * ++j]?.[y - dy * j] === role) count++;
        return count === 5 && (i = 4 -j, drawLine(x + dx * i, y + dy * i, x - dx * j, y - dy * j, WIN_LINE_WIDTH, WIN_LINE_COLOR), true);
    });


    drawBoard();
   

    const drawPiecesInOrder = (steps, isBlack) => {
            drawPiece(steps.x,steps.y, isBlack);
    };

    const a = JSON.parse(Vars.A_steps);
    const b = JSON.parse(Vars.B_steps);

    if (a){
        // const maxLength = Math.max(a.length, b.length);


        let i = 0;
        let isPrintingA = true;
        
        const interval = setInterval(() => {
            if (isPrintingA) {
                if (i < a.length) {
                    drawPiecesInOrder(a[i],true);
                }
            } else {
                if (i < b.length) {
                    drawPiecesInOrder(b[i],false);
                }
                i++; // 只有在打印完 b 之后才增加 i 的值
            }
        
            // 切换打印的数组
            isPrintingA = !isPrintingA;
        
            // 检查是否已经打印完所有元素
            if (i >= a.length && i >= b.length) {
                clearInterval(interval);
            }
        }, 500); // 每0.5秒执行一次
        
        

    }
}


export const drawPiece = (x, y, isBlack) => {
    chess[x][y] = isBlack ? 1 : 2;
    Vars.ctx.save();
    Vars.ctx.beginPath();
    x = x * Vars.W + Vars.W;
    y = y * Vars.W + Vars.W;
    Vars.ctx.arc(x, y, Vars.W * 0.4, 0, 2 * Math.PI);
    Vars.ctx.closePath();
    Vars.ctx.shadowColor = Vars.SHADOW_COLOR;
    Vars.ctx.shadowOffsetX =  Vars.ctx.shadowOffsetY = Vars.W * 0.06;
    Vars.ctx.shadowBlur = Vars.W * 0.04;
    const gradient =  Vars.ctx.createRadialGradient(x, y, 0, x, y, Vars.W * 0.4);
    gradient.addColorStop(0, isBlack ? Vars.BLACK_CHESS_TOP_COLOR : Vars.WHITE_CHESS_TOP_COLOR);
    gradient.addColorStop(1, isBlack ? Vars.BLACK_CHESS_COLOR : Vars.WHITE_CHESS_COLOR);
    Vars.ctx.fillStyle = gradient;
    Vars.ctx.fill();
    Vars.ctx.restore();
}


export const drawPieceAuto = () => {
    const SIZE = 15;
const EMPTY_ROLE = -1;
const BLACK_ROLE = 1;
const WHITE_ROLE = 2;

// 评估函数，计算当前位置在四个方向的得分
function evaluatePosition(x, y, role) {
    const directions = [
        [1, 0], [0, 1], [1, 1], [1, -1]
    ];
    let score = 0;

    directions.forEach(([dx, dy]) => {
        let count = 1;
        let block = 0;
        let empty = -1;

        for (let step = 1; step < 5; step++) {
            const nx = x + dx * step;
            const ny = y + dy * step;

            if (nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE) {
                if (chess[nx][ny] === role) {
                    count++;
                } else if (chess[nx][ny] === EMPTY_ROLE && empty === -1) {
                    empty = step;
                } else {
                    block++;
                    break;
                }
            } else {
                block++;
                break;
            }
        }

        if (empty !== -1) {
            for (let step = empty + 1; step < 5; step++) {
                const nx = x + dx * step;
                const ny = y + dy * step;

                if (nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE) {
                    if (chess[nx][ny] === role) {
                        count++;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }

        if (count >= 5) {
            score += 10000;
        } else if (block === 0 && count === 4) {
            score += 1000;
        } else if (block === 1 && count === 4) {
            score += 100;
        } else if (block === 0 && count === 3) {
            score += 100;
        } else if (block === 1 && count === 3) {
            score += 10;
        } else if (block === 0 && count === 2) {
            score += 10;
        } else if (block === 1 && count === 2) {
            score += 1;
        }
    });

    return score;
}

// 计算最佳下棋位置
 function getBestMove(isBlack) {
    const role = isBlack ? BLACK_ROLE : WHITE_ROLE;
    let bestMove = null;
    let bestValue = -Infinity;

    for (let x = 0; x < SIZE; x++) {
        for (let y = 0; y < SIZE; y++) {
            if (chess[x][y] === EMPTY_ROLE) {
                chess[x][y] = role;
                const value = evaluatePosition(x, y, role);
                chess[x][y] = EMPTY_ROLE;

                if (value > bestValue) {
                    bestValue = value;
                    bestMove = { x, y };
                }
            }
        }
    }

    return bestMove; // 返回最佳下棋位置
}

var best = getBestMove(Vars.isBlack);

console.log('best',best);

drawPiece(best.x,best.y,Vars.isBlack);



isBlack = Vars.isBlack;
            Vars.store.state.pk.socket.send(JSON.stringify({//将JSON转换为字符串
                    event: "move",
                    x: best.x,
                    y: best.y,
                    isBlack: isBlack,
                }))

            chess[best.x][best.y] = isBlack ? BLACK_ROLE : WHITE_ROLE;
            // drawBoard();

        if (isWin(best.x, best.y, chess[best.x][best.y], chess)) {
            // 发送胜利结果到服务器
            Vars.store.state.pk.socket.send(JSON.stringify({
                event: "finish",
                result: `${isBlack ? '黑' : '白'}棋赢了!`,
                isBlack: isBlack
            }));
        } else if (++moveSteps === Vars.TOTAL_STEPS) {
            // 发送平局结果到服务器
            Vars.store.state.pk.socket.send(JSON.stringify({
                event: "finish",
                result: '游戏结束，平局！',
                isBlack: null // 平局时可以设置为 null
            }));
        }

}


// export const drawBoard = () => {
//     Vars.ctx.fillStyle = Vars.BOARD_BG_COLOR;
//     Vars.ctx.fillRect(0, 0, Vars.SL, Vars.SL);
//     for (let i = 0; i < SIZE; i++) {
//         drawLine(0, i, SIZE - 1, i);
//         drawLine(i, 0, i, SIZE - 1);
//     }
// }

export const drawLine = (x1, y1, x2, y2, lineWidth = Vars.LINE_WIDTH, lineColor = Vars.LINE_COLOR) => {
    Vars.ctx.lineWidth = lineWidth;
    Vars.ctx.strokeStyle = lineColor;
    Vars.ctx.beginPath();
    Vars.ctx.moveTo(x1 * Vars.W + Vars.W, y1 * Vars.W + Vars.W);
    Vars.ctx.lineTo(x2 * Vars.W + Vars.W, y2 * Vars.W + Vars.W);
    Vars.ctx.stroke();
}



export const isWin = (x, y, role, chess) => [[1, 0], [0, 1], [1, 1], [1, -1]].some(([dx, dy]) => {
    let count = 1, i = 0, j = 0;
    while(count < 5 && chess[x + dx * ++i]?.[y + dy * i] === role) count++;
    while(count < 5 && chess[x - dx * ++j]?.[y - dy * j] === role) count++;
    return count === 5 && (i = 4 -j, drawLine(x + dx * i, y + dy * i, x - dx * j, y - dy * j, Vars.WIN_LINE_WIDTH, Vars.WIN_LINE_COLOR), true);
});



